package com.niit.qcx.PriceType;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**Reducer阶段：
 对相同价格区间的户型进行统计并计算出该区间内频数最高的户型
 输出价格区间和主要户型，如<0 - 500,3室2厅2卫>
 */
public class PriceTypeReducer extends Reducer<Text, Text, Text, Text> {
    private Map<String, Float> countMap = new HashMap<>();
    private String mostFrequentRoomType = "";

    @Override
    protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
        countMap.clear();
        mostFrequentRoomType = "";

        for (Text value : values) {
            String roomType = value.toString();
            countMap.put(roomType, countMap.getOrDefault(roomType, (float) 0) + 1);

            if (mostFrequentRoomType.isEmpty() || countMap.get(roomType) > countMap.get(mostFrequentRoomType)) {
                mostFrequentRoomType = roomType;
            }
        }

        context.write(key, new Text(mostFrequentRoomType));
    }
}

